package cn.heycm.blog.console.api;

import cn.heycm.blog.api.console.login.AdminLoginApi;
import cn.heycm.blog.api.console.login.cmd.LoginCmd;
import cn.heycm.blog.api.console.login.cmd.SendVerifyCodeCmd;
import cn.heycm.blog.api.console.login.vo.SessionVO;
import cn.heycm.blog.common.entity.result.CodeMsg;
import cn.heycm.blog.common.entity.result.Result;
import cn.heycm.blog.common.entity.session.Session;
import cn.heycm.blog.common.utils.Assert;
import cn.heycm.blog.console.domain.admin.model.Administrator;
import cn.heycm.blog.console.domain.admin.service.AdminService;
import cn.heycm.blog.console.infra.convert.ConsoleConvert;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author hey
 * @version 1.0
 * @since 2024/9/15 18:24
 */
@RestController
@Slf4j
@AllArgsConstructor
public class AdminLoginApiImpl implements AdminLoginApi {

    private final AdminService adminService;

    @Override
    public Result<Object> sendVerifyCode(SendVerifyCodeCmd cmd) {
        Administrator administrator = adminService.findAdministrator(cmd.getPhoneId());
        Assert.notNull(administrator, CodeMsg.DENY_LOGIN);
        adminService.sendVerifyCode(administrator);
        return Result.success();
    }

    @Override
    public Result<SessionVO> login(LoginCmd cmd) {
        Administrator administrator = adminService.findAdministrator(cmd.getPhoneId());
        Assert.notNull(administrator, CodeMsg.DENY_LOGIN);
        Session session = adminService.login(administrator, cmd.getVerifyCode());
        return Result.success(ConsoleConvert.INST.toVO(session));
    }
}
